package bitetorrent.helper;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;

/**
 *
 * @author user
 */
public class FileManager {

    /**
     * Menyimpan byte-byte pada file pada posisi tertentu
     * @param fileName Nama File
     * @param position Posisi awal penyimpanan
     * @param data Data yang akan disimpan
     */
    public static void saveFile(String fileName, int position, byte[] data){
        // Open File

        // Jika File belum ada buat file baru
        File file = new File(fileName);
        try
        {
            RandomAccessFile raf = new RandomAccessFile(file, "rw");
            // Seek ke position
            raf.seek(position);
            // Iterasi data dan simpan
            raf.write(data, 0, data.length);
            // Close file
            raf.close();
        }catch (IOException e) {
            System.out.println(e);
        }
    }

    public static byte[] readBlockData(String fileName, int position, int length){
        byte[] data = new byte[length];

        // Open File

        // Jika open file gagal return nulll
        File file = new File(fileName);
        try
        {
            RandomAccessFile raf = new RandomAccessFile(file, "r");
            // Seek ke position
            raf.seek(position);
            // Baca bytes sepanjang length dan simpan ke data
            raf.read(data, 0, length);
            // Close File
            raf.close();
            // Return data
        }catch (IOException e) {
            return null;
        }
        return data;
    }
    
}
